﻿using System;
using Rabbit.Model;
using System.Collections.Generic;
using System.Diagnostics;
using Rabbit.Utils; 

namespace Rabbit.BusinessLogicLayer
{
    public class UserBL
    {
        public static User CurrentUser = new User();
        public static User GetCurrentUserInformation()
        {
            string userJson = RequestHelper.SendOAuthRequest("/account/verify_credentials.json", "");
            UserSettings settings = CurrentUser.UserSettings;
            CurrentUser = WrappedJsonHelper.Deserialize<User>(userJson);
            if (settings != null)
            {
                CurrentUser.UserSettings = settings;
            }
            return CurrentUser;
        }

        //check whether a user follow me
        public static bool CheckIsFollowingMe(long userID)
        {
            string result = RequestHelper.SendOAuthRequest("friendships/exists.json", "user_a=" + userID + "&user_b=" + CurrentUser.Id);
            //due to sohu api returned bad structured json string, we need to convert it to a correct string
            result = result.Replace("{friends:", "{\"friends\":");
            return WrappedJsonHelper.Deserialize<UserRelationShip>(result).IsFriends;
        }
        //check whether a user follow me
        public static bool CheckIsFollowingMe(string userScreenName)
        {
            userScreenName = Utils.UrlEncoder.UrlOAuthEncode(userScreenName);
            string result = RequestHelper.SendOAuthRequest("friendships/exists.json", "screen_name_a=" + userScreenName + "&screen_name_a=" + CurrentUser.ScreenName);
            //due to sohu api returned bad structured json string, we need to convert it to a correct string
            result = result.Replace("{friends:", "{\"friends\":");
            return WrappedJsonHelper.Deserialize<UserRelationShip>(result).IsFriends;
        }

        public static User CreateFriendship(long userId)
        {
            string result = RequestHelper.SendOAuthRequest("/friendships/create/" + userId + ".json", "", "Post");
            return WrappedJsonHelper.Deserialize<User>(result);
        }

        public static User RemoveFriendship(long userId)
        {
            string result = RequestHelper.SendOAuthRequest("/friendships/destroy/" + userId + ".json", "", "Post");
            return WrappedJsonHelper.Deserialize<User>(result);
        }

        #region get all my following list for intelligense when publishing status
        private static List<User> followeringList = new List<User>();
        public static List<User> GetAllMyFollowingList(long CursorID, out long NextPageCursorID)
        {
            string result = RequestHelper.SendOAuthRequest(string.Format("/statuses/friends/{0}.json", CurrentUser.Id), "cursor=" + CursorID + "&count=20");

            try
            {
                Users users = WrappedJsonHelper.Deserialize<Users>(result);
                followeringList.AddRange(users.UserList);
                NextPageCursorID = users.CursorID;

                if (users.UserList.Count < 20)
                {
                    NextPageCursorID = -1;
                }

                while (users.UserList.Count == 20 && followeringList.Count <= 100)
                {
                    Debug.Print(string.Format("got {0} friends, thread.sleep 1 seconds", users.UserList.Count));
                    System.Threading.Thread.Sleep(1000);
                    GetAllMyFollowingList(users.CursorID, out NextPageCursorID);
                }

                return followeringList;
            }
            catch (Exception)
            {
                throw;
            }
        } 
        #endregion

        public static User GetUserInformationByScreenName(string name)
        {
            string result = RequestHelper.SendOAuthRequest(string.Format(
                                                                "users/show/{0}.json",
                                                                Rabbit.Utils.UrlEncoder.UrlOAuthEncode(name)
                                                                ),
                                                    "");
            return WrappedJsonHelper.Deserialize<User>(result);
        }

        public static bool UpdateUserStatus(User user,UserStatus status)
        {
            try
            {
                string param = string.Format("id={0}&name={1}&status={2}&updatetime={3}",
                    Utils.UrlEncoder.UrlEncode(user.Id.ToString()), 
                    Utils.UrlEncoder.UrlEncode(user.ScreenName), 
                    Utils.UrlEncoder.UrlEncode(((int)status).ToString()), 
                    Utils.UrlEncoder.UrlEncode(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                
                //param = string.Format("id={0}&status={1}&updatetime={2}",
                //   user.Id, (int)status, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                string result = RequestHelper.SendRequestWithSignature("status.php",param,OAuthCore.HttpMethod.POST);
                if (!string.IsNullOrEmpty(result))
                {
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
#if DEBUG
                throw;
#else
                LogHelper.LogError(ex);
                return false;
#endif
            }
        }

        public static UserStatus CheckUserStatus(User user)
        {
            string result = RequestHelper.SendRequestWithSignature(
                "status.php",
                string.Format("id={0}",user.Id),
                 OAuthCore.HttpMethod.GET);

             UserStatus status;
             if (Enum.TryParse(result,out status))
             {
                 return status;
             }
             else
             {
                 return UserStatus.Offline;
             }
        }
    }
}
